#!coding:utf-8
import binascii
class MyDes():
    # The (in)famous S-boxes
    __sbox = [
        # S1
        [14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
         0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
         4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
         15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],

        # S2
        [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
         3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
         0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
         13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],

        # S3
        [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
         13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
         13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
         1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],

        # S4
        [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
         13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
         10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
         3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],

        # S5
        [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
         14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
         4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
         11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],

        # S6
        [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
         10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
         9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
         4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],

        # S7
        [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
         13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
         1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
         6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],

        # S8
        [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
         1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
         7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
         2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],
    ]
    
    # number left rotations of pc1
    __left_rotations = [
        1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
    ]

    # initial permutation IP
    __ip = [57, 49, 41, 33, 25, 17, 9,  1,
        59, 51, 43, 35, 27, 19, 11, 3,
        61, 53, 45, 37, 29, 21, 13, 5,
        63, 55, 47, 39, 31, 23, 15, 7,
        56, 48, 40, 32, 24, 16, 8,  0,
        58, 50, 42, 34, 26, 18, 10, 2,
        60, 52, 44, 36, 28, 20, 12, 4,
        62, 54, 46, 38, 30, 22, 14, 6
    ]
    
    # final permutation IP^-1
    __fp = [
        39,  7, 47, 15, 55, 23, 63, 31,
        38,  6, 46, 14, 54, 22, 62, 30,
        37,  5, 45, 13, 53, 21, 61, 29,
        36,  4, 44, 12, 52, 20, 60, 28,
        35,  3, 43, 11, 51, 19, 59, 27,
        34,  2, 42, 10, 50, 18, 58, 26,
        33,  1, 41,  9, 49, 17, 57, 25,
        32,  0, 40,  8, 48, 16, 56, 24
    ]
    
    __pc1 = [56, 48, 40, 32, 24, 16,  8,
          0, 57, 49, 41, 33, 25, 17,
          9,  1, 58, 50, 42, 34, 26,
         18, 10,  2, 59, 51, 43, 35,
         62, 54, 46, 38, 30, 22, 14,
          6, 61, 53, 45, 37, 29, 21,
         13,  5, 60, 52, 44, 36, 28,
         20, 12,  4, 27, 19, 11,  3
    ]
    
    __pc2 = [
        13, 16, 10, 23,  0,  4,
         2, 27, 14,  5, 20,  9,
        22, 18, 11,  3, 25,  7,
        15,  6, 26, 19, 12,  1,
        40, 51, 30, 36, 46, 54,
        29, 39, 50, 44, 32, 47,
        43, 48, 38, 55, 33, 52,
        45, 41, 49, 35, 28, 31
    ]
    
    # Expansion table for turning 32 bit blocks into 48 bits
    __expansion_table = [
        31,  0,  1,  2,  3,  4,
         3,  4,  5,  6,  7,  8,
         7,  8,  9, 10, 11, 12,
        11, 12, 13, 14, 15, 16,
        15, 16, 17, 18, 19, 20,
        19, 20, 21, 22, 23, 24,
        23, 24, 25, 26, 27, 28,
        27, 28, 29, 30, 31,  0
    ]
    
    # 32-bit permutation function P used on the output of the S-boxes
    __p = [
        15, 6, 19, 20, 28, 11,
        27, 16, 0, 14, 22, 25,
        4, 17, 30, 9, 1, 7,
        23,13, 31, 26, 2, 8,
        18, 12, 29, 5, 21, 10,
        3, 24
    ]
    
    def __init__(self):
        self.subKey = [ [0] * 48 ] * 16
    
    def get_int_by_char(self,ch):
        '''将十六进制字符转换成十进制数字'''
        return int(ch,16)
    
    def number_to_BitList(self, data):
        """将数据转换成二进制数组"""
        data = [int(c,16) for c in data] #转换成十进制数
        l = len(data) * 8
        result = [0] * l
        pos = 0
        for ch in data:
            i = 7
            while i >= 0:
                if ch & (1 << i) != 0:
                    result[pos] = 1
                else:
                    result[pos] = 0
                pos += 1
                i -= 1

        return result
    
    def hex_to_BitList(self, data):
        """将数据转换成二进制数组"""
        data = [int(c,16) for c in data] #转换成十进制数
        l = len(data) * 4
        result = [0] * l
        pos = 0
        for ch in data:
            i = 3
            while i >= 0:
                if ch & (1 << i) != 0:
                    result[pos] = 1
                else:
                    result[pos] = 0
                pos += 1
                i -= 1

        return result
    
    def string_to_BitList(self, data):
        """将数据转换成二进制数组"""
        data = [ord(c) for c in data] #转换成十进制数
        l = len(data) * 8
        result = [0] * l
        pos = 0
        for ch in data:
            i = 7
            while i >= 0:
                if ch & (1 << i) != 0:
                    result[pos] = 1
                else:
                    result[pos] = 0
                pos += 1
                i -= 1

        return result
    
    def permutate(self, table, block):
        """Permutate this block with the specified table"""
        return list(map(lambda x: block[x], table))
    
    def binary2Hex(self,data):
        '''将二进制字符数组转换成16进制字符串'''
        data_len = len(data)
        if data_len>4:
            return None
        
        ord_value = 0
        for i in range(data_len):
            if data[i] == 0:
                ord_value += 0
            else:
                ord_value += (data[i]*2)**(data_len-i-1)
        return hex(ord_value)[2:]
    
    def change_ip(self,source):
        '''IP初始置换'''
        return list(map(lambda x: source[x], MyDes.__ip))
    
    def change_inverse_ip(self,source):
        '''IP最终反转置换'''
        return list(map(lambda x: source[x], MyDes.__fp))
    
    def expand(self, source):
        '''根据扩展表重新排序'''
        return list(map(lambda x: source[x], MyDes.__expansion_table))
    
    def setKey(self,key):
        self.subKey = [ [0] * 48 ] * 16
        
        key = self.permutate(MyDes.__pc1, self.string_to_BitList(key))
        
        left = key[:28]
        right = key[28:]
        #循环左移16次
        i = 0
        while i < 16:
            j = 0
            # Perform circular left shifts
            while j < MyDes.__left_rotations[i]:
                left.append(left[0])
                del left[0]

                right.append(right[0])
                del right[0]

                j += 1

            # Create one of the 16 subkeys through pc2 permutation进行PC2 置换
            self.subKey[i] = self.permutate(MyDes.__pc2, left + right)

            i += 1
        
    def crypt(self,source,key,crypt_type):
        '''加密与解密。加密与解密的不同只是做密码函数时使用轮子密钥的顺序不一样'''
        data = self.string_to_BitList(source)
        data = self.change_ip(data) #初始置换IP
        self.L = data[:32]
        self.R = data[32:]

        self.setKey(key)
        if crypt_type == 1: #解密
            iteration = 15
            iteration_adjustment = -1
        elif crypt_type == 0: #加密
            iteration = 0
            iteration_adjustment = 1

        i = 0
        while i < 16:
            # Make a copy of R[i-1], this will later become L[i]
            tempR = self.R[:]
            
            self.R = self.permutate(MyDes.__expansion_table, self.R)

            # Exclusive or R[i - 1] with K[i], create B[1] to B[8] whilst here
            self.R = list(map(lambda x, y: x ^ y, self.R, self.subKey[iteration]))
            #压力置换
            B = [self.R[:6], self.R[6:12], self.R[12:18], self.R[18:24], self.R[24:30], self.R[30:36], self.R[36:42], self.R[42:]]
            j = 0
            Bn = [0] * 32
            pos = 0
            #经过SBOX处理得到32位数据
            while j < 8:
                # Work out the offsets
                m = (B[j][0] << 1) + B[j][5]
                n = (B[j][1] << 3) + (B[j][2] << 2) + (B[j][3] << 1) + B[j][4]
                v = MyDes.__sbox[j][(m << 4) + n]
                Bn[pos] = (v & 8) >> 3
                Bn[pos + 1] = (v & 4) >> 2
                Bn[pos + 2] = (v & 2) >> 1
                Bn[pos + 3] = v & 1
                pos += 4
                j += 1
            self.R = self.permutate(MyDes.__p, Bn)
            self.R = list(map(lambda x, y: x ^ y, self.R, self.L))
            self.L = tempR

            i += 1
            iteration += iteration_adjustment
            
        self.final = self.permutate(MyDes.__fp, self.R + self.L)
        #转换成HEX字符
        leng = len(self.final)/4
        result = []
        for i in range(leng):
            data = self.final[i*4:(i+1)*4]
            result.append(self.binary2Hex(data))
        self.RESULT_HEX = ''.join(result).upper()
        
        return self.RESULT_HEX
    
    def des(self,source,key,des_type):
        source = binascii.unhexlify(source)
        key = binascii.unhexlify(key)
        return self.crypt(source, key, des_type)
    
    def genMac(self,source,mac_key):
        
        mac_key='13354058C582136F'#13354058C582136F
        data = "0200302004C030C0981000000000000000100000000102100006366222601310010029726d49121201067026870075996222601310010029726d1561560500050008168013000000010000000000ddd0702687106036303130313030383837343131303134353131323438303135365553BD291ECEB8A02000000000000000000822000001"
        
        
###        mac_key = 'C198760DB9EA49D0'
##        mac_key = self.des(mac_key, '1111111111111111', 1)
###        print 'mac_key_decrypt',mac_key
##        source='02003020048030C09810001000000000001000000001021006366222601310010029726d49121201067026870075996222601310010029726d1561560500050008168013000000010000000000ddd0702687106036303130313030383837343131303134353131323438303135365553BD291ECEB8A020000000000000000011000000010010'
###        result = '32E6C5354661BFF8'
###        print '\n*********** source is:********'
##        print len(source)
###        print '******************************'
##        MAB = []
##        #初始化MAB数组
##        leng = len(source)/16
##        for i in range(leng):
##            MAB.append(source[i*16:(i+1)*16])
##            print i,source[i*16:(i+1)*16]
##        if len(source)%16 == 0:
##            pass
##        else:
##            MAB.append(source[leng*16:]+'0'*(16-len(source)%16))
##            print leng, source[leng*16:]+'0'*(16-len(source)%16)
##        print len(MAB)
###        print MAB
##        #对MAB块依次异或
##        m0_bit = self.hex_to_BitList(MAB[0])
###        print m0_bit
##        j=1
##        while j<len(MAB):
##            m1_bit = self.hex_to_BitList(MAB[j])
##            m0_bit = list(map(lambda x,y:x^y, m0_bit, m1_bit))
##            j += 1
###        print m0_bit
##        #转换成HEX字符
##        leng2 = len(m0_bit)/4
##        result = []
##        for i in range(leng2):
##            data = m0_bit[i*4:(i+1)*4]
##            result.append(self.binary2Hex(data))
##        M0 = ''.join(result).upper()
#        
#        m0_source = binascii.b2a_hex('93CAAADB0B5A3BF6')
#        
#        
#        print m0_source
#        M0_DES = self.des(m0_source[:16], mac_key, 0)
#        M0_DES_BIT = self.hex_to_BitList(M0_DES)
#        print M0_DES
#        print 'M0_DES_BIT',M0_DES_BIT
#        print m0_source[16:32]
#        TEMP = list(map(lambda x,y:x^y,M0_DES_BIT,self.hex_to_BitList(m0_source[16:32])))
##        print 'M0[8:26]',M0[8:16]
##        print self.number_to_BitList(M0[8:16])
##        print TEMP
#        len_temp = len(TEMP)/4
#        result_temp = []
#        for i in range(len_temp):
#            data = TEMP[i*4:(i+1)*4]
##            print data
##            print self.binary2Hex(data)
#            result_temp.append(self.binary2Hex(data))
#        temp_hex = ''.join(result_temp).upper()
##        print 'temp_hex is:',temp_hex
#        temp_block = self.des(temp_hex, mac_key, 0)
##        print '\n***************temp block is:***************'
##        print temp_block
##        print '********************************************\n'
#        
#        mac = temp_block[:16].upper()
#        print 'mac is',mac
#        return mac[:8]
    
if __name__ == '__main__':
    myDes = MyDes()
    #myDes.genMac('source', '')
    print myDes.crypt('9D3683EEB4EB27F8', '1111111111111111', 1)
#    source = 'AE7907F7DADAA4A1'
#    key = '1111111111111111'
#    PIN = myDes.des(source, key, 1)
#    print PIN
#    
#    result = []
#    enc_res = myDes.des('0000000000000000',PIN,0)  #使用PIN_Hex对8个数字0进行加密
#    print enc_res
    
#    04A1CEE597AE13FD
#    0AC0D360F60C6383

